package com.origin.utils.time


import android.util.Log
import java.lang.StringBuilder
import java.text.SimpleDateFormat
import java.util.*


import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.*

import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

object TimeUtil {

    /**
     * 扩展方法
     * 倒计时的实现
     */
    fun AppCompatActivity.countDown(
        time: Int = 30,
        start: (scop: CoroutineScope) -> Unit,
        next: (time: String) -> Unit,
        end: () -> Unit
    ) {
        lifecycleScope.launch {
            // 在这个范围内启动的协程会在Lifecycle被销毁的时候自动取消
            flow {
                (time downTo 0).forEach {
                    delay(1000)
                    emit(it)
                }
            }.onStart {
                // 倒计时开始 ，在这里可以让Button 禁止点击状态
                start(this@launch)
            }.onCompletion {
                // 倒计时结束 ，在这里可以让Button 恢复点击状态
                end()
            }.catch {
                //错误
                Log.e("", it.message ?: "Unkown Error")
            }.collect {
                // 在这里 更新值来显示到UI
                next(it.toString())
            }
        }
    }



    interface TimerImp {
        fun run()
    }

    fun timer(period: Long = 1000, timerImp: TimerImp): Timer {
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                timerImp.run()
            }

        }, Date(), period)
        return timer;
    }

    //1是星期日
    fun getWeek() = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)


    /**
     * 秒级转换成时间格式
     */
    fun secondToTime(s: Long): String {
        var second = s
        val days = second / 86400;//转换天数
        second %= 86400;//剩余秒数
        val hours = second / 3600;//转换小时数
        second %= 3600;//剩余秒数
        val minutes = second / 60;//转换分钟
        second %= 60;//剩余秒数
        return if (0 < days) {
            "${days}天，${hours}小时，${minutes}分，${second}秒"
        } else {
            var str = ""
            if (hours < 10) {
                str += "0$hours"
            } else {
                str += hours
            }
            if (hours == 0L) {
                str = "";
            } else {
                str += ":"
            }



            if (minutes < 10) {
                str += "0$minutes"
            } else {
                str += minutes
            }
            str += ":"
            if (second < 10) {
                str += "0$second"
            } else {
                str += second
            }
            str
        }


    }

    /**
     * 计算出时间差
     */
    fun distanceTime(time1: Long, time2: Long): TimeBean {
        val timeBean = TimeBean.getInstance()
        val day: Long
        val hour: Long
        val min: Long
        val sec: Long
        val diff: Long = if (time1 < time2) {
            time2 - time1;
        } else {
            time1 - time2;
        }
        day = diff / (24 * 60 * 60 * 1000);
        timeBean.day = day
        hour = (diff / (60 * 60 * 1000) - day * 24);
        timeBean.hour = hour
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        timeBean.min = min
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        timeBean.sec = sec

        return timeBean

    }


    val dayStr = "yyyy/MM/dd"

    /**
     * 根据时间格式转换
     */

    @Synchronized
    fun timeFormat(date: Date = Date(System.currentTimeMillis()), format: String): String {
        val simpleDateFormat = SimpleDateFormat(format, Locale.ROOT);// HH:mm:ss
        return simpleDateFormat.format(date)
    }

    /**
     *
     * 精确到天
     */
    fun getNowDay(): String {

        return timeFormat(format = "yyyy/MM/dd")

    }


    /**
     *
     * 精确到毫秒
     */
    @JvmStatic
    fun getNowTime(): String {

        return timeFormat(format = "yyyy/MM/dd-HH:mm:ss:SSS")

    }


    fun stampToDate(lt: Long): String {

        var res = ""
        if (lt / 1000000000000 >= 0) {
            res = stampToDate13(lt)
        } else
            if (lt / 1000000000 >= 0) {
                res = stampToDate10(lt)
            }
        return res

    }

    /**
     * 13位的秒级别的时间戳
     */

    @JvmStatic
    fun stampToDate13Alpha(lt: Long): String {
        return timeFormat(Date(lt), "yyyy/MM/dd HH:mm")
    }

    /**
     * 13位的秒级别的时间戳
     */

    fun stampToDate13(lt: Long): String {
        return timeFormat(Date(lt), "yyyy/MM/dd HH:mm:ss")
    }

    /**
     * 10位的秒级别的时间戳
     */
    fun stampToDate10(lt: Long): String {

        return timeFormat(Date(lt * 1000), "yyyy/MM/dd HH:mm:ss")
    }

    @JvmStatic
    fun getNowYear(): String {
        return timeFormat(format = "yyyy")
    }


}